package mylog

import (
	"sync"
	"encoding/json"
	"fmt"
	"os"
	"time"
	"path/filepath"
	"mygo/myws"
)


var mu sync.Mutex


func MyLog(mesg myws.Mesg, ipaddr, mpath string) error {
    mu.Lock()
    defer mu.Unlock()

    data, err := json.Marshal(mesg)
    if err != nil {
        return err
    }
    // 获取当前日期和时间
    now := time.Now()
    date := now.Format("2006-01-02")
    timestamp := now.Format("15:04:05")

    // 根据日期创建日志文件
    filename := fmt.Sprintf("%s.log", date)
    file, err := os.OpenFile(filepath.Join(mpath, filename), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return err
    }
    defer file.Close()

    // 将内容写入日志文件
    _, err = file.WriteString(fmt.Sprintf("[%s] [%s] %s: %s\n", date, timestamp, ipaddr, string(data)))
    if err != nil {
        return err
    }
    return nil
}

func ErrLog(data, mpath string) error {
    mu.Lock()
    defer mu.Unlock()

    // 获取当前日期和时间
    now := time.Now()
    date := now.Format("2006-01-02")
    timestamp := now.Format("15:04:05")

    // 根据日期创建日志文件
    filename := fmt.Sprintf("error_%s.log", date)
    file, err := os.OpenFile(filepath.Join(mpath, filename), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return err
    }
    defer file.Close()

    // 将内容写入日志文件
    _, err = file.WriteString(fmt.Sprintf("[%s] [%s]: %s\n", date, timestamp, data))
    if err != nil {
        return err
    }
    return nil
}

